#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
import threading

# 存储所有客户端的连接
clients = []

def handle_client(conn, addr):
    """处理客户端连接"""
    print(f"[NEW CONNECTION] {addr} connected.")
    clients.append(conn)

    try:
        while True:
            message = conn.recv(1024)
            if not message:
                break
            print(f"[{addr}] {message.decode('utf-8')}")
            broadcast(message, conn)
    except Exception as e:
        print(f"[ERROR] {e}")
    finally:
        print(f"[DISCONNECTED] {addr} disconnected.")
        clients.remove(conn)
        conn.close()

def broadcast(message, conn):
    """向所有客户端广播消息，除了发送者"""
    for client in clients:
        if client != conn:
            try:
                client.send(message)
            except:
                clients.remove(client)

def start_server():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(("0.0.0.0", 12345))
    server.listen()
    print("[STARTING] Server is starting...")

    while True:
        conn, addr = server.accept()
        thread = threading.Thread(target=handle_client, args=(conn, addr))
        thread.start()

if __name__ == "__main__":
    start_server()
